package ui.activity;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.fy.fyzf.R;
import com.fy.fyzf.base.BaseActivity;
import com.fy.fyzf.bean.AddHousingBean;
import com.fy.fyzf.bean.DeleteImgBean;
import com.fy.fyzf.bean.HouseDongBean;
import com.fy.fyzf.bean.HousingDetailBean;
import com.fy.fyzf.bean.HousingSearchBean;
import com.fy.fyzf.bean.BaseData;
import com.fy.fyzf.dialog.AddOwnerdialog;
import com.fy.fyzf.dialog.DeleteWarningDialog;
import com.fy.fyzf.dialog.LoopViewPopwindow;
import com.fy.fyzf.dialog.SelectHousingPopwindow;
import com.fy.fyzf.oss.MyOSSUtils;
import com.fy.fyzf.presenter.AddhousingPresenter;
import com.fy.fyzf.utils.AppUtils;
import com.fy.fyzf.utils.BitmapUtils;
import com.fy.fyzf.utils.MathUtils;
import com.fy.fyzf.utils.SPUtils;
import com.fy.fyzf.view.AddHouingCallBack;
import com.fy.fyzf.weight.CustomProgressDialog;
import com.fy.fyzf.weight.FullyGridLayoutManager;
import com.fy.fyzf.weight.GlideEngine;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.broadcast.BroadcastAction;
import com.luck.picture.lib.broadcast.BroadcastManager;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.decoration.GridSpacingItemDecoration;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;
import com.luck.picture.lib.style.PictureParameterStyle;
import com.luck.picture.lib.tools.ScreenUtils;
import com.luck.picture.lib.tools.SdkVersionUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.lang.ref.WeakReference;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import ui.adapter.GridImageAdapter;
import ui.adapter.ImagePickerListAdapter;

//添加房源
public class EditHousingActivity extends BaseActivity<AddhousingPresenter> implements /*BGASortableNinePhotoLayout.Delegate,*/ AddHouingCallBack,MyOSSUtils.OssUpCallback {

    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.leftView)
    TextView leftView;
    @BindView(R.id.tv_center_title)
    TextView tvCenterTitle;
    @BindView(R.id.rightImage)
    ImageView rightImage;
    @BindView(R.id.right)
    TextView rightText;
    @BindView(R.id.titleBar)
    RelativeLayout titleBar;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.titleLine)
    View titleLine;
    @BindView(R.id.tv_quality)
    TextView tvQuality;
    @BindView(R.id.et_quality)
    TextView etQuality;
    @BindView(R.id.tv_owner)
    TextView tvOwner;
    @BindView(R.id.et_owner)
    TextView etOwner;
    @BindView(R.id.tv_loupan)
    TextView tvLoupan;
    @BindView(R.id.et_loupan)
    EditText etLoupan;
    @BindView(R.id.tv_dong)
    TextView tvDong;
    @BindView(R.id.et_dong)
    TextView etDong;
    @BindView(R.id.tv_subway)
    TextView tvSubway;
    @BindView(R.id.et_subway)
    TextView etSubway;
    @BindView(R.id.tv_louceng)
    TextView tvLouceng;
    @BindView(R.id.et_louceng)
    TextView etLouceng;
    @BindView(R.id.huhao)
    TextView huhao;
    @BindView(R.id.tv_huhao)
    TextView tvHuhao;
    @BindView(R.id.fenhu)
    TextView fenhu;
    @BindView(R.id.tv_fenhu)
    TextView tvFenhu;
    @BindView(R.id.area)
    TextView area;
    @BindView(R.id.et_area)
    EditText etArea;
    @BindView(R.id.yongtu)
    TextView yongtu;
    @BindView(R.id.tv_purpose)
    TextView tvPurpose;
    @BindView(R.id.price)
    TextView price;
    @BindView(R.id.et_price)
    EditText etRentPrice;
    @BindView(R.id.zhuangtai)
    TextView zhuangtai;
    @BindView(R.id.tv_status)
    TextView tvStatus;
    @BindView(R.id.zhuangxiu)
    TextView zhuangxiu;
    @BindView(R.id.tv_fitment_status)
    TextView tvFitmentStatus;
    @BindView(R.id.gongsi)
    TextView gongsi;
    @BindView(R.id.tv_company)
    TextView tvCompany;
    @BindView(R.id.staff)
    TextView staff;
    @BindView(R.id.tv_add_staff)
    TextView tvAddStaff;
    @BindView(R.id.price2)
    TextView price2;
    @BindView(R.id.tv_price2)
    EditText tvPrice2;
    @BindView(R.id.yngjin)
    TextView yngjin;
    @BindView(R.id.tv_yongjin)
    EditText tvYongjin;
    @BindView(R.id.tv_look_type)
    EditText tvLookType;
    @BindView(R.id.tv_rent_fee_time)
    EditText tvRentFeeTime;
    @BindView(R.id.tv_pay_type)
    EditText tvPayType;
    @BindView(R.id.tv_year_time)
    EditText tvYearTime;
    @BindView(R.id.tv_spec_remark)
    EditText tvSpecRemark;
    @BindView(R.id.tv_owner_info)
    TextView tvOwnerInfo;
    @BindView(R.id.et_sell_price)
    EditText etSellPrice;
    @BindView(R.id.linear)
    LinearLayout linearLayout;
    @BindView(R.id.ll_owner)
    LinearLayout llOwner;
//    @BindView(R.id.snpl_moment_add_photos)
//    BGASortableNinePhotoLayout mPhotosSnpl;
    @BindView(R.id.ll_rent)
    LinearLayout llrent;
    @BindView(R.id.ll_sell)
    LinearLayout llSell;
    @BindView(R.id.recycleView)
    RecyclerView mRecyclerView;
    @BindView(R.id.tv_ok)
    TextView tvOk;
    @BindView(R.id.scrollView)
    NestedScrollView nestedScrollView;
    private AddHousingBean addHousingBean;
    private ImagePickerListAdapter mImagePickerAdapter;
    private GridImageAdapter mAdapter;
    private StringBuilder stringBuilder;  //图片上传之后拼接的字符
    //    private HousingDetailBean housingData;
    private int housingId;
    private List<LocalMedia> netImgList; //接口获取的网络图片数据
    private List<HousingDetailBean.HousingImagesBean> housingImages;
    private int type;

    @Override
    protected AddhousingPresenter createPresenter() {
        return new AddhousingPresenter(this);
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_add_housing;
    }

    @Override
    public void initView() {
        super.initView();
        setTitleName("编辑房源");
        etDong.setClickable(false);
        addHousingBean = new AddHousingBean();
        tvQuality.setText(showColorText("*优质房"));
        tvOwner.setText(showColorText("*是否大业主"));
        tvLoupan.setText(showColorText("*楼盘"));
        tvLouceng.setText(showColorText("*楼层"));
        tvDong.setText(showColorText("*栋座"));
        tvSubway.setText(showColorText("*地铁"));
        huhao.setText(showColorText("*户号"));
        fenhu.setText(showColorText("*分户"));
        area.setText(showColorText("*面积"));
        yongtu.setText(showColorText("*用途"));
        price.setText(showColorText("*出租价格"));
        zhuangtai.setText(showColorText("*状态"));
        zhuangxiu.setText(showColorText("*装修情况"));
        gongsi.setText(showColorText("*所属公司"));
        staff.setText(showColorText("*添加员工"));
        llOwner.setVisibility(View.GONE);
//        tvAddStaff.setText(SPUtils.getInstance(EditHousingActivity.this).getString("name", ""));
//        tvCompany.setText(SPUtils.getInstance(EditHousingActivity.this).getString("company", ""));

//        housingData = (HousingDetailBean) getIntent().getParcelableExtra("data")

        etLoupan.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }
            @Override
            public void afterTextChanged(Editable s) {
                isShow = true;
                mPresenter.fuzzyQueryFloor(s.toString().trim());
            }
        });
        etRentPrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(etArea.getText().toString())) {

                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s)) {
                    return;
                }

            }
        });
        etRentPrice.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    if (TextUtils.isEmpty(etRentPrice.getText().toString())) {
                        return;
                    }
                    if (Double.parseDouble(etRentPrice.getText().toString()) > 50) {
                        BigDecimal divide = new BigDecimal(etRentPrice.getText().toString()).divide(new BigDecimal(30), 2, BigDecimal.ROUND_HALF_UP);
                        BigDecimal divide1 = divide.divide(new BigDecimal(etArea.getText().toString()), 2, BigDecimal.ROUND_HALF_UP);
                        AlertDialog.Builder alertdialogbuilder = new AlertDialog.Builder(EditHousingActivity.this);
                        alertdialogbuilder.setMessage("系统检测到您填写的是总价格"+etRentPrice.getText().toString()+"元，自动为您计算价格为："+divide1+"元/m²/天");
                        etRentPrice.setText(String.valueOf(divide1));
                      /*  alertdialogbuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        });*/
                        final AlertDialog alertdialog1 = alertdialogbuilder.create();
                        alertdialog1.show();
                    }
                } else {
                    if (TextUtils.isEmpty(etArea.getText().toString())) {
                        AppUtils.showToast("请先填写面积");
                        etArea.setFocusable(true);
                        etArea.setFocusableInTouchMode(true);
                        etArea.requestFocus();
                    }
                }
            }
        });
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this,
                4, GridLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(manager);

        mRecyclerView.addItemDecoration(new GridSpacingItemDecoration(4,
                ScreenUtils.dip2px(this, 8), false));

        mAdapter = new GridImageAdapter(EditHousingActivity.this, onAddPicClickListener);

        if (savedInstanceState != null && savedInstanceState.getParcelableArrayList("selectorList") != null) {
            mAdapter.setList(savedInstanceState.getParcelableArrayList("selectorList"));
        }

        mAdapter.setSelectMax(100);
        mAdapter.isSupportDelete(false);
        mRecyclerView.setAdapter(mAdapter);

       /* mAdapter.setOnDeleteListener(new GridImageAdapter.OnItemDeleteListener() {
            @Override
            public void onDelete(int position) {
//                localMediaList.remove(position);
                if (null != housingImages.get(position).getHousingImageId()) {
                    Log.e("删除id", "" + housingImages.get(position).getHousingImageId());
                    DeleteImgBean deleteImgBean = new DeleteImgBean();
                    deleteImgBean.setHousingImageId(housingImages.get(position).getHousingImageId());
                    mPresenter.deleteHousingImg(deleteImgBean);
                }
            }
        });*/
//        mAdapter.setOnItemClickListener();
        stringBuilder = new StringBuilder();
        BroadcastManager.getInstance(this).registerReceiver(broadcastReceiver,
                BroadcastAction.ACTION_DELETE_PREVIEW_POSITION);
    }

    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {
            PictureSelector.create(EditHousingActivity.this)
                    .openGallery(PictureMimeType.ofImage())
                    .imageEngine(GlideEngine.createGlideEngine())
                    .theme(R.style.picture_default_style)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style v2.3.3后 建议使用setPictureStyle()动态方式
                    .isWeChatStyle(true)// 是否开启微信图片选择风格
                    .isUseCustomCamera(false)// 是否使用自定义相机
                    .setLanguage(-1)// 设置语言，默认中文
                    .setPictureStyle(new PictureParameterStyle())// 动态自定义相册主题
//                        .setPictureCropStyle(mCropParameterStyle)// 动态自定义裁剪主题
                    .setPictureWindowAnimationStyle(null)// 自定义相册启动退出动画
                    .isWithVideoImage(true)// 图片和视频是否可以同选,只在ofAll模式下有效
                    .isMaxSelectEnabledMask(true)// 选择数到了最大阀值列表是否启用蒙层效果
                    .maxSelectNum(100)// 最大图片选择数量
                    .minSelectNum(1)// 最小选择数量
                    .maxVideoSelectNum(1) // 视频最大选择数量
                    .imageSpanCount(3)// 每行显示个数
                    .isReturnEmpty(false)// 未选择数据时点击按钮是否可以返回
                    .closeAndroidQChangeWH(true)//如果图片有旋转角度则对换宽高,默认为true
                    .closeAndroidQChangeVideoWH(!SdkVersionUtils.checkedAndroid_Q())// 如果视频有旋转角度则对换宽高,默认为false
                    .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)// 设置相册Activity方向，不设置默认使用系统
                    .isOriginalImageControl(false)// 是否显示原图控制按钮，如果设置为true则用户可以自由选择是否使用原图，压缩、裁剪功能将会失效
                    .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选
                    .isSingleDirectReturn(true)// 单选模式下是否直接返回，PictureConfig.SINGLE模式下有效
                    .isPreviewImage(true)// 是否可预览图片
                    .isPreviewVideo(false)
                    //.querySpecifiedFormatSuffix(PictureMimeType.ofJPEG())// 查询指定后缀格式资源
                    .isEnablePreviewAudio(false) // 是否可播放音频
                    .isCamera(true)// 是否显示拍照按钮
                    //.isMultipleSkipCrop(false)// 多图裁剪时是否支持跳过，默认支持
                    //.isMultipleRecyclerAnimation(false)// 多图裁剪底部列表显示动画效果
                    .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                    .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg,Android Q使用PictureMimeType.PNG_Q
                    .isEnableCrop(false)// 是否裁剪
                    .isCompress(true)// 是否压缩
                    .synOrAsy(false)//同步true或异步false 压缩 默认同步
                    //.queryMaxFileSize(10)// 只查多少M以内的图片、视频、音频  单位M
                    //.compressSavePath(getPath())//压缩图片保存地址
                    //.sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效 注：已废弃
                    //.glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度 注：已废弃
                    .isGif(false)// 是否显示gif图片
                    .freeStyleCropEnabled(false)// 裁剪框是否可拖拽
                    .circleDimmedLayer(false)// 是否圆形裁剪
                    .showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
                    .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
                    .isOpenClickSound(false)// 是否开启点击声音
                    .selectionData(mAdapter.getData())// 是否传入已选图片
                    .cutOutQuality(90)// 裁剪输出质量 默认100
                    .minimumCompressSize(100)// 小于多少kb的图片不压缩
//                        .forResult(PictureConfig.CHOOSE_REQUEST);
                    .forResult(new MyResultCallback(mAdapter));

        }
    };
    private int imgSize = 0;
    private List<LocalMedia> localMediaList;//本地图片数据

    @Override
    public void successImg(String img_url) {
        i++;
        imgList.add(img_url);
        //每上传完成一次 i自增 i == 全部图片数量 减去 网络图片数量（netImgList.size() - netImgCount） 代表全部上传完成
        if (i == netImgList.size() - netImgCount) {
            CustomProgressDialog.stopLoading();
            addHousingBean.setImages(imgList);
            Log.e("finalImgData", new Gson().toJson(addHousingBean));
            mPresenter.editHousing(addHousingBean);
        }

    }

    @Override
    public void successVideo(String video_url) {

    }

    @Override
    public void inProgress(long progress, long zong) {

    }

    /**
     * 返回结果回调
     */
    private class MyResultCallback implements OnResultCallbackListener<LocalMedia> {
        private WeakReference<GridImageAdapter> mAdapterWeakReference;

        public MyResultCallback(GridImageAdapter adapter) {
            super();
            this.mAdapterWeakReference = new WeakReference<>(adapter);
        }

        @Override
        public void onResult(List<LocalMedia> result) {
            imgSize = result.size();
            localMediaList = result;
//            netImgList.addAll(result);
            netImgList = result;
            Log.e("添加", new Gson().toJson(netImgList));

//            CustomProgressDialog.showLoading(AddHousingActivity.this);
            if (mAdapterWeakReference.get() != null) {
                mAdapterWeakReference.get().setList(netImgList);
                mAdapterWeakReference.get().notifyDataSetChanged();
            }
        }

        @Override
        public void onCancel() {
        }
    }

    @Override
    public void initData() {
        super.initData();

        housingId = getIntent().getIntExtra("id", -1);
        type = getIntent().getIntExtra("type", 0);
        if (type == 3 || type == 4) {
            linearLayout.setVisibility(View.GONE);
        } else if (type == 5) {
            rightText.setVisibility(View.VISIBLE);
            rightText.setText("删除房源");
        } else {
            nestedScrollView.fullScroll(ScrollView.FOCUS_DOWN);
        }
        mPresenter.getHousingDetail(housingId);
    }

    private static final int RC_CHOOSE_PHOTO = 1;
    private static final int PRC_PHOTO_PICKER = 1;
    private static final int RC_PHOTO_PREVIEW = 2;

    private SpannableStringBuilder showColorText(String s) {
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(s);
        spannableStringBuilder.setSpan(new ForegroundColorSpan(Color.parseColor("#E12002")), 0, 1, spannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableStringBuilder.setSpan(new ForegroundColorSpan(Color.parseColor("#333333")), 1, s.length(), spannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spannableStringBuilder;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
        }
    }

    private int netImgCount = 0;//网络图片数量

    @OnClick({R.id.right,R.id.tv_owner_info, R.id.tv_ok, R.id.tv_fenhu, R.id.titleLine, R.id.et_quality, R.id.et_owner, R.id.et_loupan, R.id.et_dong, R.id.et_louceng, R.id.tv_huhao, R.id.tv_purpose, R.id.tv_status, R.id.tv_fitment_status})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.right:
                showDeleteDialog();
                break;
            case R.id.tv_owner_info:
                addOwner();
                break;
            case R.id.tv_ok:
                Log.e("imgData", netImgList.size() + "  " + new Gson().toJson(netImgList));
                CustomProgressDialog.showLoading(this);
                File file;
                addHousingBean.setSellPrice(etSellPrice.getText().toString().trim());
                addHousingBean.setHousingId(housingId);
                addHousingBean.setUserId(Integer.parseInt(SPUtils.getInstance(this).getString("userId", "")));
                addHousingBean.setFollowPrice(tvPrice2.getText().toString());
                addHousingBean.setFollowCommission(tvYongjin.getText().toString());
                addHousingBean.setFollowWay(tvLookType.getText().toString());
                addHousingBean.setDecorateFreetime(tvRentFeeTime.getText().toString());
                addHousingBean.setSigningYear(tvPayType.getText().toString());
                addHousingBean.setDecorateFreetime(tvRentFeeTime.getText().toString());
                addHousingBean.setFollowSpecial(tvSpecRemark.getText().toString());
                addHousingBean.setHousingArea(Double.parseDouble(etArea.getText().toString()));

                addHousingBean.setRentPrice(etRentPrice.getText().toString());
                addHousingBean.setFollowIncreasing(tvYearTime.getText().toString());
                //有网络图片和本地图片同时出现在数组的情况 上传的时候 只需要上传本地图片就行 通过图片地址是否以http开头来区分
                // 先从混合数组中把网络图片单独取出来  本地图片全部上传成功之后 再组合
                if (null == localMediaList || localMediaList.size() <= 0) {
                    addHousingBean.setImages(null);
                    mPresenter.editHousing(addHousingBean);
                } else {
                    for (int j = 0; j < netImgList.size(); j++) {
                        if (netImgList.get(j).getPath().startsWith("http") || netImgList.get(j).getPath().startsWith("https")) {
//                            imgList.add(netImgList.get(j).getPath());
                            netImgCount++;
                        } else {
                            if (android.os.Build.VERSION.SDK_INT == 29) { //判断是否是AndroidQ
                                file = new File(netImgList.get(j).getAndroidQToPath());
                            } else {
                                file = new File(netImgList.get(j).getPath());
                            }
                            RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                            Bitmap bitmap = BitmapFactory.decodeFile(file.getPath());
                            File imgFIle = BitmapUtils.compressImage2(bitmap);
                            MultipartBody.Part body = MultipartBody.Part.createFormData("file", imgFIle.getName(), requestFile);
//                            mPresenter.upLoadImg(body);
                            if (android.os.Build.VERSION.SDK_INT == 29) {
                                MyOSSUtils.getInstance().upImage(EditHousingActivity.this,EditHousingActivity.this, System.currentTimeMillis() + ".jpg", netImgList.get(j).getAndroidQToPath());
                            } else {
                                MyOSSUtils.getInstance().upImage(EditHousingActivity.this,EditHousingActivity.this, System.currentTimeMillis() + ".jpg", netImgList.get(j).getPath());

                            }

                        }

                    }
                }

                break;
            case R.id.titleLine:

                break;
            case R.id.et_quality: //是否质量房  0 否 1是
                List<String> titles = new ArrayList<>();
                titles.add("是");
                titles.add("否");

                List<Integer> idS = new ArrayList<>();
                idS.add(1);
                idS.add(0);

                getValue(1, 1, titles, idS, "是否优质房", etQuality);

                break;
            case R.id.et_owner:
                titles = new ArrayList<>();
                titles.add("是");
                titles.add("否");

                idS = new ArrayList<>();
                idS.add(1);
                idS.add(0);
                getValue(2, 1, titles, idS, "是否优质房", etOwner);

                break;
            case R.id.et_loupan:
                break;
            case R.id.et_dong:
                if (floorId == null) {
                    AppUtils.showToast("请先选择楼盘");
                }
                mPresenter.getFloorList(floorId);

                break;
            case R.id.et_louceng:
                titles = new ArrayList<>();
                idS = new ArrayList<>();
                for (int i = 1; i < 70; i++) {
                    titles.add(String.format("%02d", i));
                    idS.add(i);
                }
                titles.get(getValue(4, 3, titles, idS, "选择楼层", etLouceng));


                break;
            case R.id.tv_huhao:
                titles = new ArrayList<>();
                idS = new ArrayList<>();
                for (int i = 1; i < 41; i++) {
                    titles.add(String.format("%02d", i));
                    idS.add(i);
                }
                getValue(5, 3, titles, idS, "选择户号", tvHuhao);
                break;
            case R.id.tv_fenhu:
                titles = new ArrayList<>();
                idS = new ArrayList<>();
                titles.add("未分户");
                idS.add(null);
                for (int i = 1; i < 11; i++) {
                    titles.add(String.format("%02d", i));
                    idS.add(i);
                }
                getValue(6, 3, titles, idS, "选择分户", tvFenhu);
//                addHousingBean.setHousehold(titles.get(getValue(2, titles, idS, "选择户号", tvFenhu)));
                break;
            case R.id.tv_purpose:
                titles = new ArrayList<>();
                idS = new ArrayList<>();
                titles.add("出租");
                titles.add("出售");
                titles.add("可租可售");

                idS.add(0);
                idS.add(1);
                idS.add(2);
                getValue(7, 2, titles, idS, "选择用途", tvPurpose);
                break;
            case R.id.tv_status:
                titles = new ArrayList<>();
                idS = new ArrayList<>();
                titles.add("有效");
                titles.add("已租");
                titles.add("暂缓");
                titles.add("我租");
                titles.add("租售");
                titles.add("我售");
                titles.add("非有效");

                for (int i = 1; i <= 7; i++) {
                    idS.add(i);
                }
                getValue(8, 4, titles, idS, "选择状态", tvStatus);

                break;
            case R.id.tv_fitment_status:
                titles = new ArrayList<>();
                idS = new ArrayList<>();
                titles.add("无装修");
                titles.add("简装");
                titles.add("精装");
                titles.add("豪装");

                idS.add(4);
                idS.add(1);
                idS.add(2);
                idS.add(3);
                getValue(9, 4, titles, idS, "装修情况", tvFitmentStatus);

                break;
        }
    }

    private void showDeleteDialog() {
        DeleteWarningDialog deleteWarningDialog = new DeleteWarningDialog(this);
        deleteWarningDialog.setContent("是否删除此房源?");
        deleteWarningDialog.toggleDialog();
        deleteWarningDialog.getView(R.id.tv_sure).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deleteWarningDialog.toggleDialog();
                mPresenter.deleteHousing(housingId);

            }
        });
    }

    private List<AddHousingBean.OwnerParamListBean> ownerInfList = new ArrayList<>();

    private String addOwner() {
        AddOwnerdialog addOwnerdialog = new AddOwnerdialog(EditHousingActivity.this);
        addOwnerdialog.toggleDialog();
        addOwnerdialog.getView(R.id.tv_sure).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(addOwnerdialog.etName.getText().toString())) {
                    AppUtils.showToast("请输入业主姓名");
                    return;
                }
                if (TextUtils.isEmpty(addOwnerdialog.etTel.getText().toString())) {
                    AppUtils.showToast("请输入业主电话");
                    return;
                }
                if (TextUtils.isEmpty(addOwnerdialog.etTel.getText().toString()) || addOwnerdialog.etTel.getText().toString().length() < 6) {
                    AppUtils.showToast("手机号不正确");
                    return;
                }
//                OwnerInfBean ownerInfBean = new OwnerInfBean();
                AddHousingBean.OwnerParamListBean ownerParamListBean = new AddHousingBean.OwnerParamListBean();
                ownerParamListBean.setOwnerMobile(addOwnerdialog.etTel.getText().toString());
                ownerParamListBean.setOwnerName(addOwnerdialog.etName.getText().toString());
                ownerParamListBean.setOwnerRemark(addOwnerdialog.etRemark.getText().toString());
                ownerInfList.add(ownerParamListBean);
                addHousingBean.setOwnerParamList(ownerInfList);

                tvOwnerInfo.setText(addOwnerdialog.etName.getText().toString());
                addOwnerdialog.toggleDialog();
            }
        });
        return addOwnerdialog.etName.getText().toString();
    }

    private Integer getValue(int i, int type, List<String> titles, List<Integer> idS, String name, TextView textView) {
        LoopViewPopwindow loopViewPopwindow = new LoopViewPopwindow(this);
        loopViewPopwindow.setIds(idS).setTitleData(titles).setTitle(name).showPop(etQuality);
        loopViewPopwindow.getView(R.id.tv_sure).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (i == 1) { //质量房
                    addHousingBean.setQualityHouse(loopViewPopwindow.getSelectValue());
                    if (loopViewPopwindow.getSelectValue() == 0) {
                        textView.setText("否");
                    } else {
                        textView.setText("是");
                    }
                } else if (i == 2) {
                    //大业主
                    addHousingBean.setBigOwner(loopViewPopwindow.getSelectValue());
                    if (loopViewPopwindow.getSelectValue() == 0) {
                        textView.setText("否");
                    } else {
                        textView.setText("是");
                    }
                } else if (i == 3) {
                    //栋座
                    textView.setText(loopViewPopwindow.getSelectName());
                    addHousingBean.setBuildingName(loopViewPopwindow.getSelectName());
                    addHousingBean.setBuildingId(idS.get(loopViewPopwindow.position));
                } else if (i == 4) {
                    addHousingBean.setFloor(loopViewPopwindow.getSelectName());
                    textView.setText(loopViewPopwindow.getSelectName());
                } else if (i == 5) {  //户号
                    addHousingBean.setRoomNumber(loopViewPopwindow.getSelectName());
                    textView.setText(loopViewPopwindow.getSelectName());
                } else if (i == 6) {//分户
                    textView.setText(loopViewPopwindow.getSelectName());
                    if (loopViewPopwindow.position == 0) {
                        addHousingBean.setHousehold("未分户");
                    } else {
                        addHousingBean.setHousehold("-" + loopViewPopwindow.getSelectName());
                    }
                } else if (i == 7) {
                    //用途
                    textView.setText(titles.get(loopViewPopwindow.getSelectValue()));
                    addHousingBean.setHousingPurpose(idS.get(loopViewPopwindow.position));

                    if (loopViewPopwindow.position == 0) {
                        llSell.setVisibility(View.VISIBLE);
                        llrent.setVisibility(View.GONE);
                    } else if (loopViewPopwindow.position == 1) {
                        llrent.setVisibility(View.VISIBLE);
                        llSell.setVisibility(View.GONE);
                    } else {
                        llrent.setVisibility(View.VISIBLE);
                        llSell.setVisibility(View.VISIBLE);
                    }
                } else if (i == 8) {
                    //状态
                    textView.setText(titles.get(loopViewPopwindow.position));
                    addHousingBean.setHousingStatus(idS.get(loopViewPopwindow.position));
                } else if (i == 9) {
                    //装修情况
                    addHousingBean.setRenovationType(idS.get(loopViewPopwindow.position));
                    textView.setText(titles.get(loopViewPopwindow.position));
                }

                /*if (type == 1) {

                } else if (type == 3) {
                    textView.setText(loopViewPopwindow.getSelectName());
                } else if (type == 4) {
                    textView.setText(titles.get(loopViewPopwindow.position));
                } else {
                    textView.setText(titles.get(loopViewPopwindow.getSelectValue()));
                }*/
                loopViewPopwindow.dismiss();
            }
        });
        return loopViewPopwindow.getSelectValue();
    }

    private Integer floorId;
    private boolean isShow;

    private Integer getHousingName(List<String> titles, List<Integer> idS, String name, TextView text) {
        SelectHousingPopwindow selectHousingPopwindow = new SelectHousingPopwindow(this);
        selectHousingPopwindow.setIds(idS).setTitleData(titles).setTitle(name).showPop(etQuality);
        selectHousingPopwindow.getView(R.id.tv_sure).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                text.setText(titles.get(selectHousingPopwindow.getSelectValue()));
                etSubway.setText(housIngList.get(selectHousingPopwindow.getSelectValue()).getSubwayName());
                floorId = housIngList.get(selectHousingPopwindow.getSelectValue()).getFloorId();
                addHousingBean.setFloorId(floorId);
                selectHousingPopwindow.dismiss();
                etLoupan.setText(titles.get(selectHousingPopwindow.getSelectValue()));
                isShow = false;
                addHousingBean.setFloorName(etLoupan.getText().toString().trim());
            }
        });
        return selectHousingPopwindow.getSelectValue();
    }

    private List<HousingSearchBean> housIngList;

    @Override
    public void fuzzyQueryFloorSuccess(List<HousingSearchBean> list) {
        housIngList = list;
        List<String> titles = new ArrayList<>();
        List<Integer> idS = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            titles.add(list.get(i).getFloorName());
            idS.add(list.get(i).getFloorId());
        }
        if (isShow) {
            Integer i = getHousingName(titles, idS, "选择楼盘", etLoupan);
        }
    }

    @Override
    public void getFloorListSuccess(HouseDongBean houseDongBean) {
        ArrayList<String> titles = new ArrayList<>();
        ArrayList<Integer> idS = new ArrayList<>();
        for (int i = 0; i < houseDongBean.getBuildingVoList().size(); i++) {
            titles.add(houseDongBean.getBuildingVoList().get(i).getBuilding());
            idS.add(houseDongBean.getBuildingVoList().get(i).getBuildingId());
        }
        //设置栋座id

        getValue(3, 3, titles, idS, "选择栋座", etDong);
//        etDong.setText(titles.get(getValue(3, titles, idS, "选择栋座", etDong)));
    }

    private int i;
    private List<String> imgList = new ArrayList<>();

    @Override
    public void upLoadImgSuccess(BaseData baseData) {
        i++;
        imgList.add(baseData.data.toString());
        //每上传完成一次 i自增 i == 全部图片数量 减去 网络图片数量（netImgList.size() - netImgCount） 代表全部上传完成
        if (i == netImgList.size() - netImgCount) {
            CustomProgressDialog.stopLoading();
            addHousingBean.setImages(imgList);
            Log.e("finalImgData", new Gson().toJson(addHousingBean));
            mPresenter.editHousing(addHousingBean);
        }
    }

    @Override
    public void getHousingDetailSuccess(HousingDetailBean housingData) {
        //文档房间号就是户号
        Log.e("房源数据", new Gson().toJson(housingData));
        addHousingBean.setQualityHouse(housingData.getQualityHouse());
        addHousingBean.setBuildingId(housingData.getBuildingId());
        if (housingData.getQualityHouse() == 0) {
            etQuality.setText("否");
        } else {
            etQuality.setText("是");
        }
        etLouceng.setText(housingData.getHousingNoNum().getFloor());
        tvHuhao.setText(housingData.getHousingNoNum().getRoomNumber());
        addHousingBean.setBigOwner(housingData.getBigOwner());
        addHousingBean.setFloorId(housingData.getFloorId());
        floorId = housingData.getFloorId();
        if (housingData.getBigOwner() == 0) {
            etOwner.setText("否");
        } else {
            etOwner.setText("是");
        }
        tvAddStaff.setText(housingData.getUserName());
        tvCompany.setText(housingData.getCompanyName());
        etSellPrice.setText(housingData.getSellPrice());
        etLoupan.setText(housingData.getFloorName());
        isShow = false;
        addHousingBean.setFloorName(etLoupan.getText().toString());
        etDong.setText(housingData.getBuilding());
        addHousingBean.setBuildingName(etDong.getText().toString());

        etSubway.setText(housingData.getSubwayName());
        addHousingBean.setSubwayName(etSubway.getText().toString());
//        etLoupan.setText(addHousingBean.getFloor()); //楼层号
        HousingDetailBean.HousingNoNumBean housingNoNum = housingData.getHousingNoNum();//房间信息
        addHousingBean.setFloor(housingNoNum.getFloor());

        addHousingBean.setRoomNumber(housingData.getHousingNoNum().getRoomNumber());
        if (null == housingData.getHousingNoNum().getHousehold()) {
            addHousingBean.setHousehold("未分户");
            tvFenhu.setText("未分户");
        } else {
            tvFenhu.setText(housingData.getHousingNoNum().getHousehold());
            addHousingBean.setHousehold(housingData.getHousingNoNum().getHousehold() + "");
        }
        addHousingBean.setHousingArea(Double.parseDouble(housingData.getHousingArea()));
        etArea.setText(MathUtils.rvZeroAndDot(housingData.getHousingArea()));
        addHousingBean.setHousingPurpose(housingData.getHousingPurpose());
        if (housingData.getHousingPurpose() == 0) {
            tvPurpose.setText("出租");
        } else if (housingData.getHousingPurpose() == 1) {
            tvPurpose.setText("出售");
        } else {
            tvPurpose.setText("可租可售");
            llrent.setVisibility(View.VISIBLE);
        }

        addHousingBean.setSellPrice(housingData.getSellPrice());
        etRentPrice.setText(MathUtils.rvZeroAndDot(housingData.getRentPrice()));
        addHousingBean.setHousingStatus(housingData.getHousingStatus());
        switch (housingData.getHousingStatus()) {
            case 1:
                tvStatus.setText("有效");
                break;
            case 2:
                tvStatus.setText("已租");
                break;
            case 3:
                tvStatus.setText("暂缓");

                break;
            case 4:
                tvStatus.setText("我租");
                break;
            case 5:
                tvStatus.setText("租售");
                break;
            case 6:
                tvStatus.setText("我售");
                break;
            case 7:
                tvStatus.setText("非有效");
                break;
        }
        addHousingBean.setRenovationType(housingData.getRenovationType());
        switch (housingData.getRenovationType()) {
            case 1:
                tvFitmentStatus.setText("简装");
                break;
            case 2:
                tvFitmentStatus.setText("精装");
                break;
            case 3:
                tvFitmentStatus.setText("豪装");
                break;
            case 4:
                tvFitmentStatus.setText("无装修");
        }
        addHousingBean.setFollowPrice(housingData.getFollowPrice());
        tvPrice2.setText(housingData.getFollowPrice());
        addHousingBean.setFollowWay(housingData.getFollowWay());
        tvLookType.setText(housingData.getFollowWay());

        addHousingBean.setFollowCommission(housingData.getFollowCommission());
        tvYongjin.setText(housingData.getFollowCommission());

        addHousingBean.setDecorateFreetime(housingData.getDecorateFreetime());
        tvRentFeeTime.setText(housingData.getDecorateFreetime());

        addHousingBean.setSigningYear(housingData.getSigningYear()); //这个字段实际是付款方式
        tvPayType.setText(housingData.getSigningYear());

        addHousingBean.setFollowIncreasing(housingData.getFollowIncreasing());
        tvYearTime.setText(housingData.getFollowIncreasing());

        addHousingBean.setFollowSpecial(housingData.getFollowSpecial());
        tvSpecRemark.setText(housingData.getFollowSpecial());
//        addHousingBean.set  //设置业主信息

        //这个列表带图片id
        housingImages = housingData.getHousingImages();
        netImgList = new ArrayList<>();

        for (int j = 0; j < housingImages.size(); j++) {
            LocalMedia localMedia = new LocalMedia();
            localMedia.setCutPath(housingImages.get(j).getHousingImage());
            localMedia.setPath(housingImages.get(j).getHousingImage());
            localMedia.setAndroidQToPath(housingImages.get(j).getHousingImage());
//            localMedia.set
            netImgList.add(localMedia);
        }
        mAdapter.setList(netImgList);
        mAdapter.notifyDataSetChanged();
        Log.e("图片数据", new Gson().toJson(netImgList));
    }

    @Override
    public void addHousingSuccess(BaseData baseData) {

    }

    @Override
    public void editHousingSuccess(BaseData baseData) {
        CustomProgressDialog.stopLoading();
        AppUtils.showToast("修改成功");
        finish();
        EventBus.getDefault().post("housingEditSuccess");
    }

    @Override
    public void deleteHousingSuccess(BaseData baseData) {
        AppUtils.showToast("删除成功");
        EventBus.getDefault().post("deleteHousing");
        finish();

    }

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (TextUtils.isEmpty(action)) {
                return;
            }
            if (BroadcastAction.ACTION_DELETE_PREVIEW_POSITION.equals(action)) {
                // 外部预览删除按钮回调
                Bundle extras = intent.getExtras();
                if (extras != null) {
                    int position = extras.getInt(PictureConfig.EXTRA_PREVIEW_DELETE_POSITION);
                    mAdapter.remove(position);
                    mAdapter.notifyItemRemoved(position);
                }
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (broadcastReceiver != null) {
            BroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver,
                    BroadcastAction.ACTION_DELETE_PREVIEW_POSITION);
        }
    }
}